﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DomainModel;

namespace Utils
{
    public enum EmailTemplateType
    {
        SignUp = 1,
        ResetPassword = 2,
        JobPackagePayment = 3,
        ContactInd = 4
    }

    public class EmailTemplateUtils
    {
        public static EmailTemplate BuildEmailTemplate(int emailTemplateType, string[] args = null)
        {
            var template = SqlUtilities.Query<EmailTemplate>(ConstUtils.SP_GetEmailTemplateByType, 
                new { EmailTemplateType = emailTemplateType }).FirstOrDefault();
            if (template != null && template.EmailTemplateID > 0)
            {
                //split by ","
                string[] parameters = CommonUtilities.GetEmailTemplateBodyParameterArray(template.BodyParameter);
                //compare args count
                int argsCount = args == null ? 0 : args.Length;
                int tempParamCount = parameters == null ? 0 : parameters.Length;
                if (argsCount == tempParamCount)
                {
                    string result = template.Body;
                    //replace param, case-insenstive replacement
                    for (int i = 0; i < parameters.Length; i++ )
                    {
                        //extension replace method
                        result = result.Replace(parameters[i], args[i], StringComparison.OrdinalIgnoreCase);
                    }
                    template.Body = result;
                    return template;
                }
                else
                {
                    throw new Exception("the passed-in args' count doesn't match the email template parameters' count, type is " + emailTemplateType + ", args are " + args.ToString());
                }
            }
            else
            {
                throw new Exception("Can't find the email template which type is " + emailTemplateType);
            }
        }
    }

}
